package com.jxj.study.controller;

import com.jxj.study.util.PdfUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

//https://blog.csdn.net/hgx2014/article/details/88849482
//https://blog.csdn.net/qq_37195258/article/details/125063844
public class PDFDemoController {

    public static void main(String[] args) {
        File file = new File("D:\\test.pdf");
        OutputStream outputStream = null;
//        OutputStream outputStream = response.getOutputStream();
        Writer writer =null;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Map<String, Object> variables = new HashMap<>();
        variables.put("staffName", "staffName");
        variables.put("functions", "functions");
        variables.put("assessmentDate", "assessmentDate");
        variables.put("roles", "roles");
        variables.put("aggregateSource", "aggregateSource");
        variables.put("questionList", null);
        variables.put("comments", null);
        variables.put("score", "score");
        variables.put("signature", "signature");
        variables.put("paperName","paperName");
        variables.put("assessmentTypeName","info.getAssessmentTypeName()");
        variables.put("pdfFileName","test");
        variables.put("isagree",true);
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
        try {
            outputStream = new FileOutputStream(file);
            // 获取模版路径
            cfg.setDirectoryForTemplateLoading(ResourceUtils.getFile("classpath:templates"));
            Template freemarkerTemplate = cfg.getTemplate("/test.ftlh");
            writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
            freemarkerTemplate.process(variables, writer);
            String htmlContent = outStream.toString("utf-8");
            PdfUtil.buildPdf(outputStream,htmlContent);
        }catch (Exception e) {
           e.printStackTrace();
        }
        finally {
            try {
                outStream.close();
                if (outputStream != null){
                    outputStream.close();
                }
                if (writer != null){
                    writer.close();
                }
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
    }
}